package com.dongdong.SmsService.impl;

import com.dongdong.SmsService.SmsService;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/19 11:02
 * @Version 1.0
 **/
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate redisTemplate;
    /*发送短信需要的参数:
    * 接收人的手机号
    *短信内容
    * code 验证码
    * */
    @Override
    public void sendCode(String phone) {
        //初始化client,apikey作为所有请求的默认值(可以为空)
        YunpianClient clnt = new YunpianClient("d32c3ef2084614187ddf796a839333cc").init();
        Map<String, String> param = clnt.newParam(2);
        //获取随机数
        String code = RandomStringUtils.randomNumeric(6);
        //加缓存
        HashOperations hash = redisTemplate.opsForHash();
        hash.put("phoneCode:",phone,code);
        redisTemplate.expire("phone:",1, TimeUnit.HOURS);
        param.put(YunpianClient.MOBILE, phone);
        param.put(YunpianClient.TEXT, "【梁惠】您的验证码是"+ code +"。如非本人操作，请忽略本短信");
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        r.getData();
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*

        //最后释放client
        clnt.close();
    }
}

